const GOODSKEY = "goods"

//查询商品
export const getGoodsObj = () => {
    const goodsStr = localStorage.getItem(GOODSKEY) || '{}'
        
    return JSON.parse(goodsStr)
}

//添加商品
export const addGoodsObj = (goods)=>{
    const localStorageGoods = getGoodsObj()

    if(localStorageGoods[goods.goodsId]){
        localStorageGoods[goods.goodsId] += goods.count
    }else{
        localStorageGoods[goods.goodsId] = goods.count
    }

    //保存起来
    localStorage.setItem(GOODSKEY,JSON.stringify(localStorageGoods))

    return getTotalCount()
}

//更新商品
export const updateGoodsObj = (goods) => {
    const localStorageGoods = getGoodsObj()

    localStorageGoods[goods.goodsId] = goods.count

     //保存起来
    localStorage.setItem(GOODSKEY,JSON.stringify(localStorageGoods))

    return getTotalCount()
}

//根据id删除商品
export const deleteGoodsObj = (goodsId) => {
    const localStorageGoods = getGoodsObj()

    delete localStorageGoods[goodsId]

    //保存起来
    localStorage.setItem(GOODSKEY,JSON.stringify(localStorageGoods))

    return getTotalCount()
}

//获取加入购物车中的商品总数
export const getTotalCount = () =>{
    const localStorageGoods = getGoodsObj()

    let totalCount  = 0
    for(const key in localStorageGoods){
        totalCount+=localStorageGoods[key]
    }

    return totalCount
}